package org.codeart.api_driver.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.codeart.common.constant.TokenEnum;
import org.codeart.common.dto.TokenResult;
import org.codeart.common.util.JwtUtils;
import org.codeart.common.util.R;
import org.codeart.common.util.RedisPrefixUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        boolean flag = true;
        String result = "";
        String token = request.getHeader("Authorization");
        TokenResult tokenResult = JwtUtils.checkToken(token);
        if (tokenResult == null) {
            result = "token invalid";
            flag = false;
        } else {
            // 从redis取出token
            String phone = tokenResult.getPhone();
            String identity = tokenResult.getIdentity();
            String tokenKey = RedisPrefixUtil.generateTokenKey(phone, identity, TokenEnum.ACCESS_TOKEN.value());
            String redisToken = redisTemplate.opsForValue().get(tokenKey);
            if (StrUtil.isEmpty(redisToken) || !token.trim().equals(redisToken.trim())) {
                result = "token invalid";
                flag = false;
            }
        }
        
        if (!flag) {
            PrintWriter out = response.getWriter();
            out.print(JSONUtil.toJsonStr(R.fail(result)));
        }
        return flag;
    }
}
